<template>
  <div>
    <el-card>
      <!-- 头部功能区 -->
      <el-row>
        <el-form inline size="mini" ref="ruleForm" :model="query">
          <!-- <el-form-item>
            <el-button type="primary" @click="getData(true)">告警列表</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getData(false)">告警工单列表</el-button>
          </el-form-item> -->
          <el-form-item label="严重性" prop="severity">
            <el-select
              v-model="query.severity"
              placeholder="请选择严重性"
              style="margin-right: 10px"
              size="mini"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="问题" prop="name">
            <el-input v-model="query.name" placeholder="请输入问题" />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getData(alarmOrList)"
              >搜索</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button
              type="warning"
              @click="
                resetForm('ruleForm');
                getData(alarmOrList);
              "
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </el-row>

      <!-- 告警处理编辑弹框 -->
      <el-row>
        <el-dialog title="告警处理" :visible.sync="dialogFormVisible">
          <el-form ref="form" :model="form" label-width="80px" :rules="rules">
            <el-form-item label="问题">
              <el-input v-model="form.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="消息">
              <el-input
                type="textarea"
                v-model="form.message"
                placeholder="请输入消息"
              ></el-input>
            </el-form-item>
            <el-form-item label="范围" prop="scope1">
              <el-radio-group v-model="form.scope1">
                <el-radio label="1">只选择问题</el-radio>
                <el-radio label="2">已选择的和其他问题的关联触发器</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="更改严重性" label-width="140" prop="severity">
              <el-radio-group v-model.number="form.severity">
                <el-radio :label="0">未分类</el-radio>
                <el-radio :label="1">信息</el-radio>
                <el-radio :label="2">警告</el-radio>
                <el-radio :label="3">一般严重</el-radio>
                <el-radio :label="4">严重</el-radio>
                <el-radio :label="5">灾难</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="AddAssociationType('form')"
              >更新</el-button
            >
          </div>
        </el-dialog>
      </el-row>

      <!-- 生成工单弹框 -->
      <el-dialog title="生成工单" :visible.sync="workOrderVisible">
        <el-form :model="order">
          <el-form-item label="事件工单" label-width="100px">
            <el-select
              v-model="order.region"
              placeholder="请选择事件工单"
              @change="initData()"
            >
              <el-option
                v-for="item in processList"
                :key="item.deploymentId"
                :label="item.processName"
                :value="item.definitionId"
              ></el-option>
            </el-select>
          </el-form-item>
          <div class="form-conf" v-if="formOpen">
            <parser
              :key="new Date().getTime()"
              :form-conf="formData"
              @submit="submit"
              ref="parser"
              @getData="getData"
            />
          </div>
        </el-form>
      </el-dialog>

      <!-- 列表 -->
      <el-row>
        <el-table
          :data="tableData"
          style="width: 100%"
          height="calc(100vh - 190px)"
          :default-sort="{ prop: 'date', order: 'descending' }"
        >
          <el-table-column
            show-overflow-tooltip="ture"
            prop="beginTime"
            label="开始时间"
          >
            <template slot-scope="scope">
              <el-tag type="primary" size="mini">{{
                scope.row.beginTime
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="continueTime" label="持续时间">
            <template slot-scope="scope">
              <el-tag type="primary" size="mini">{{
                scope.row.continueTime | getTime
              }}</el-tag>
            </template>
          </el-table-column>
          <!-- <el-table-column
            show-overflow-tooltip="ture"
            prop="endTime"
            label="结束时间"
          >
            <template slot-scope="scope">
              <el-tag type="primary" size="mini">{{
                scope.row.endTime
              }}</el-tag>
            </template>
          </el-table-column> -->
          <el-table-column
            show-overflow-tooltip="ture"
            prop="severity"
            align="center"
            label="严重性"
          >
            <template slot-scope="scope">
              <el-tag type="danger" size="mini">{{
                scope.row.severity | getSeverity
              }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            show-overflow-tooltip="ture"
            prop="status"
            label="状态"
          >
            <template slot-scope="scope">
              <el-tag type="success" size="mini">{{
                scope.row.status == "1" ? "未解决" : "已解决"
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip="ture"
            prop="hostName"
            label="主机"
          >
          </el-table-column>
          <el-table-column
            show-overflow-tooltip="ture"
            prop="name"
            label="问题"
          >
          </el-table-column>
          <el-table-column
            show-overflow-tooltip="ture"
            prop="action"
            label="自愈"
          >
          </el-table-column>
          <el-table-column
            show-overflow-tooltip="ture"
            prop="comments"
            label="详情"
          >
          </el-table-column>
          <el-table-column label="操作" align="center" width="300">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                style="margin-right: 10px"
                @click="GenerateWorkOrder(scope.row)"
                >生成工单</el-button
              >
              <el-button
                slot="reference"
                size="mini"
                type="danger"
                @click="showAlarmHandle(scope.row)"
                >告警处理</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- <pagination
          v-show="tableData.length > 0"
          :total="tableData.length"
          :page.sync="query.pageNum"
          :limit.sync="query.pageSize"
          @pagination="getListData"
        /> -->
      </el-row>
    </el-card>
  </div>
</template>
<script>
import Parser from "@/utils/generator/parser";
import {
  getAlarmList_Api, //告警管理列表查询
  alarmHandle_Api, //告警处理
  getEventAlarmList_Api, //查询添加工单告警列表
} from "@/api/automated/alarm.js";
import {
  listProcess,
  getProcessForm,
  startProcess,
} from "@/api/workflow/process";

export default {
  components: {
    Parser,
  },
  data() {
    return {
      order: {
        region: "",
      },
      workOrderVisible: false,
      //告警列表或工单列表
      alarmOrList: true, //true 告警列表
      eventList: [], //工单列表
      query: {
        severity: null, //严重级别
        name: null, //问题
        // pageSize: 10,
        // pageNum: 1,
      },
      //编辑表单
      form: {
        name: null, //问题名称
        eventids: null, //时间id
        severity: null, //严重级别
        message: "", //消息
        action: "8", //操作选项
        scope1: "1", //范围（scope好像是个关键字不能用？使用scope验证不成功）
        scope: null, //发送的范围内
      },
      loading: false,
      dialogFormVisible: false, //新增显示隐藏
      //严重性
      options: [
        {
          value: "0",
          label: "未分类",
        },
        {
          value: "2",
          label: "警告",
        },
        {
          value: "4",
          label: "严重",
        },
        {
          value: "1",
          label: "信息",
        },
        {
          value: "3",
          label: "一般严重",
        },
        {
          value: "5",
          label: "灾难",
        },
      ],
      //列表数据
      tableData: [],
      //表单验证
      rules: {
        //名称
        scope1: [{ required: true, message: "请选择范围", trigger: "change" }],
      },
      processList: [],
      deployId: null,
      definitionId: null,
      formOpen: false,
      formData: {},
      rowData: {},
    };
  },
  methods: {
    //获取问题工单
    getIssues() {
      listProcess({
        pageNum: 1,
        pageSize: 1000,
        processKey: null,
        processName: null,
        category: "SJGL",
      }).then((response) => {
        this.processList = response.rows;
      });
    },
    //获取告警管理列表数据
    getData(boo) {
      this.alarmOrList = boo;
      if (this.alarmOrList) {
        //告警
        getAlarmList_Api(this.query).then((res) => {
          this.tableData = res.data;
        });
      } else {
        //工单
        getEventAlarmList_Api(this.query).then((res) => {
          this.tableData = res.rows;
        });
      }
    },
    //确认告警处理
    AddAssociationType(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.scope = this.form.scope1;
          alarmHandle_Api(this.form).then((res) => {
            this.$message.success(res.msg);
            this.form = {
              name: null, //问题名称
              eventids: null, //时间id
              severity: null, //严重级别
              message: "", //消息
              action: "8", //操作选项
              scope1: "1", //范围
              scope: null,
            };
            this.dialogFormVisible = false;
            this.getFormData(true);
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //显示告警处理弹框
    showAlarmHandle(data) {
      this.dialogFormVisible = true;
      this.form.name = data.name;
      this.form.eventids = data.eventid;
      this.form.severity = data.severity;
    },
    //重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //跳转发起流程页面
    eventBase(row) {
      this.$router.push({
        path: "/workflow/process/eventStart",
        query: row,
      });
    },
    //展示生成工单
    GenerateWorkOrder(row) {
      this.workOrderVisible = true;
      this.order.region = null;
      this.formOpen = false;
      this.rowData = row;
    },
    //下拉框选择表单
    initData() {
      const obj = this.processList.find((item) => {
        if (item.definitionId == this.order.region) {
          return true;
        }
      });
      this.definitionId = obj.definitionId;

      getProcessForm({
        definitionId: this.definitionId,
        deployId: obj.deploymentId,
      }).then((res) => {
        // console.log(this.rowData);
        if (res.data) {
          this.formData = res.data;
          this.formData.fields.forEach((item) => {
            switch (item.__config__.label) {
              case "问题名称":
                item.__config__.defaultValue = this.rowData.name;
                break;
              case "问题描述":
                item.__config__.defaultValue = this.rowData.description;
                break;
              case "来源工单ID":
                item.__config__.defaultValue = this.rowData.eventid;
                break;
              case "来源类型":
                item.__config__.defaultValue = "告警管理";
                break;
            }
          });
          // this.formData.fields[0].__config__.defaultValue = this.rowData.name;
          // this.formData.fields[1].__config__.defaultValue =
          //   this.rowData.description;
          // this.formData.fields[2].__config__.defaultValue =
          //   this.rowData.eventid;
          // this.formData.fields[3].__config__.defaultValue = "告警管理";
          this.formOpen = true;
        }
      });
    },
    //  接收子组件传的值
    getFormData(data) {
      if (data) {
        const variables = [];
        data.fields.forEach((item) => {
          let variableData = {};
          variableData.label = item.__config__.label;
          // 表单值为多个选项时
          if (item.__config__.defaultValue instanceof Array) {
            const array = [];
            item.__config__.defaultValue.forEach((val) => {
              array.push(val);
            });
            variableData.val = array;
          } else {
            variableData.val = item.__config__.defaultValue;
          }
          variables.push(variableData);
        });
        this.variables = variables;
      }
    },
    submit(data) {
      if (data && this.definitionId) {
        // 启动流程并将表单数据加入流程变量
        startProcess(this.definitionId, JSON.stringify(data.valData)).then(
          (res) => {
            this.$modal.msgSuccess(res.msg);
            this.$tab.closeOpenPage({
              path: "/centralized/event_management",
            });
          }
        );
      }
    },
    /** 流程流转记录 */
    handleFlowRecord(row) {
      this.$router.push({
        path: "/workflow/process/detail/" + row.procInsId,
        query: {
          processed: false,
        },
      });
    },
  },
  created() {
    this.getData(true); //告警列表查询
    this.getIssues();
  },
  filters: {
    //过滤严重性
    getSeverity(val) {
      switch (val) {
        case 0:
          return "未分类";
        case 1:
          return "信息";
        case 2:
          return "警告";
        case 3:
          return "一般严重";
        case 4:
          return "严重";
        case 5:
          return "灾难";
      }
    },
    //持续时间过滤器
    getTime(durationStr) {
      if (!durationStr) {
        return "";
      }
      let days = "";
      let hours = "";
      let minutes = "";
      let seconds = "";
      if (durationStr.indexOf("h") == -1 && durationStr.indexOf("m") == -1) {
        //没有 h 和 m
        durationStr = "0h0m" + durationStr;
      } else if (durationStr.indexOf("h") == -1) {
        //没有 h
        durationStr = "0h" + durationStr;
      } else if (durationStr.indexOf("m") == -1) {
        //没有 m
        durationStr =
          durationStr.split("h")[0] + "h0m" + durationStr.split("h")[1];
      }
      days = Math.floor(durationStr.split("h")[0] / 24) + "天";
      days == "0天" ? (days = "") : null;
      hours = Math.floor(durationStr.split("h")[0] % 24) + "小时";
      days == "" && hours == "0小时" ? (hours = "") : null;
      minutes = durationStr.split("h")[1].split("m")[0] + "分";
      days == "" && hours == "" && minutes == "0分" ? (minutes = "") : null;
      seconds = durationStr.split("m")[1].split("s")[0] + "秒";
      return days + hours + minutes + seconds;
    },
  },
};
</script>
<style lang="scss" scoped></style>
